import Taro, { useCallback, useRef } from '@tarojs/taro'
import { Animated, Easing } from 'react-native'

function useAnimation(defaultState, duration) {
  const animation = useRef(
    (() => {
      const animationData = {}
      Object.keys(defaultState).forEach((key) => {
        animationData[key] = new Animated.Value(defaultState[key])
      })
      return animationData
    })()
  ).current

  const setAnimationState = useCallback(
    (newState, newDuration, newTimingFunction, callback) => {
      const animationSequenceList = unifromArray(newState)
        .map((state, i) => {
          if (newDuration === 0) {
            Object.keys(state).forEach((key) => {
              animation[key].setValue(state[key])
            })
            return
          }

          const animationList = Object.keys(state).map((key) => {
            return Animated.timing(animation[key], {
              toValue: state[key],
              useNativeDriver: true,
              easing: easingMap[newTimingFunction],
              duration: compareValue(unifromArray(newDuration)[i], duration)
            })
          })

          if (animationList.length === 1) return animationList[0]
          return Animated.parallel(animationList)
        })
        .filter((a) => a)

      if (animationSequenceList.length === 1) {
        animationSequenceList[0].start(callback)
      } else {
        Animated.sequence(animationSequenceList).start(callback)
      }
    },
    [animation, duration]
  )

  const newAnimation = { ...animation }
  let animationData = {}

  if (Object.keys(newAnimation).indexOf('opacity') > -1) {
    animationData = { opacity: animation.opacity }
    delete newAnimation.opacity
  }
  if (Object.keys(newAnimation).length) {
    animationData = { ...animationData, transform: Object.keys(newAnimation).map((key) => ({ [key]: animation[key] })) }
  }
  console.log(22333, animationData)

  return [animationData, setAnimationState]
}

const compareValue = (newDuration, oldValue) => (newDuration === undefined ? oldValue : newDuration)
const unifromArray = (value) => (Array.isArray(value) ? value : [value])

const easingMap = {
  'linear': Easing.linear,
  'ease': Easing.ease,
  'ease-in': Easing.in(Easing.ease),
  'ease-in-out': Easing.inOut(Easing.ease),
  'ease-out': Easing.out(Easing.ease),
  'step-start': Easing.step0,
  'step-end': Easing.step1
}

export default useAnimation
